﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Security;
using System.Drawing;
using System.IO;

using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

namespace WebChatClient.Controllers
{
    public class LogInController : Controller
    {
        IWebService service;
        
        List<Chatter> ListChatter;
 

        private static OpenIdRelyingParty openid = new OpenIdRelyingParty();


        public LogInController()
        {

            service = new WebChatService("http://localhost:63046/");

            ListChatter = new List<Chatter>();
        }




        //
        // GET: /LogIn/

        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Index(Chatter chatter)
        {
            Chatter Me = GetCurrentChatterModel(chatter.Nick);

            if (ModelState.IsValid)
            {
                if (IsChatterValid(chatter))
                {
                    Me.Status = 1;
                    HttpResponseMessage response = service.Put("api/ChatterAPI/" + Me.Id, Me);
                        
                    if (response.IsSuccessStatusCode)
                    {

                    }

                    FormsAuthentication.SetAuthCookie(chatter.Nick, false);
                    return RedirectToAction("Index", "Home");
                }
                {
                    ModelState.AddModelError("", "Invalid username or password");
                }
            }
            return View();
        }


        public bool IsChatterValid(Chatter chatter)
        {
            HttpResponseMessage response = service.Get("api/ChatterAPI");
                // Blocking call!

            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var products = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in products)
                {
                    ListChatter.Add(p);
                }

            }
            else
            {
                return false;
            }

            //Compare with each in ListChatter

            for (int i = 0; i < ListChatter.Count; i++)
            {
                if ((chatter.Nick == ListChatter[i].Nick) && (chatter.Password == ListChatter[i].Password))
                    return true;
            }
            return false;
        }


        private Chatter GetCurrentChatterModel(string name)
        {
            Chatter tempchatter = new Chatter();
            string CurrentUserNick = name;


            // Get the chatter list from the server
            HttpResponseMessage response = service.Get("api/ChatterAPI");
               // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var products = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in products)
                {
                    ListChatter.Add(p);
                }
            }

            //Compare the name to get right model

            for (int i = 0; i < ListChatter.Count; i++)
            {
                if (ListChatter[i].Nick == CurrentUserNick)
                    tempchatter = ListChatter[i];
            }
            return tempchatter;
        }


        public ActionResult LogInOpenID()
        {
            return View();
        }



        [ValidateInput(false)]
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();
            


            if (response == null)
            {
                //Let us submit the request to OpenID provider
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(
                                             Request.Form["openid_identifier"]);

                        var fields = new ClaimsRequest();
                        fields.Email = DemandLevel.Require;
                        fields.FullName = DemandLevel.Require;

                        request.AddExtension(fields);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewBag.Message = ex.Message;
                        return View("Index");
                    }
                }

                ViewBag.Message = "Invalid identifier";
                return View("Index");
            }

            //Let us check the response
            switch (response.Status)
            {

                case AuthenticationStatus.Authenticated:

                    string provider = response.Provider.Uri.ToString();
                    Uri ChatterUri = null;
                    Chatter OpenIDChatter = new Chatter();
                    var claimResponse = response.GetExtension<ClaimsResponse>();

                    string email = claimResponse.MailAddress.ToString();

                    IOpenIDAccountCreationStrategy _openIDcreationstrategy;
                    _openIDcreationstrategy = OpenIDAccCreationFactory.GetCreationStrategy(provider);

                    OpenIDChatter = _openIDcreationstrategy.CreateOpenIDAccount(email);


                    if (!IsChatterValid(OpenIDChatter))
                    {
                        HttpResponseMessage httpresponse = service.Post("api/ChatterAPI", OpenIDChatter);
                            


                        if (httpresponse.IsSuccessStatusCode)
                        {
                            ChatterUri = httpresponse.Headers.Location;
                            FormsAuthentication.SetAuthCookie(OpenIDChatter.Nick, false);
                            return RedirectToAction("Index", "Home");
                        }
                    }                                   

                    FormsAuthentication.SetAuthCookie(OpenIDChatter.Nick, false);
                     return RedirectToAction("Index", "Home");

                case AuthenticationStatus.Canceled:
                    ViewBag.Message = "Canceled at provider";
                    return View("Index");
                case AuthenticationStatus.Failed:
                    ViewBag.Message = response.Exception.Message;
                    return View("Index");
            }

            return new EmptyResult();
        }




    }
}
